package kr.hkit.androidcomplete02.cp;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class EnglishWordEx extends Activity {
	
	private WordDBManager mDbManager;
	private SimpleCursorAdapter cursorAdapter;
	
	private static final String[] columns = {"_id", "eng", "han" };
	private static final int[] to = {R.id.listnum, R.id.listeng, R.id.listhan};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.englishwordex);
		
		mDbManager = WordDBManager.getInstance(this);
		ListView list = (ListView) findViewById(R.id.word_list);
		
		Cursor cursor = mDbManager.select(columns, null, null, null, null, null);
		startManagingCursor(cursor);
		cursorAdapter = new SimpleCursorAdapter(this,R.layout.list_row, cursor, 
				columns, to, cursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		list.setAdapter(cursorAdapter);
		
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		mDbManager.close();
	}

	
	public void mOnClick(View v) {
		String whereClause=null;
		String[] whereArgs;
		
		switch (v.getId()) {
		case R.id.insertbtn:
			EditText eng = (EditText) findViewById(R.id.engedit);
			EditText han = (EditText) findViewById(R.id.hanedit);
			ContentValues addRowValue = new ContentValues();
			addRowValue.put("eng", eng.getText().toString());
			addRowValue.put("han", han.getText().toString());
			mDbManager.insert(addRowValue);
			eng.setText("");han.setText("");
			break;
		case R.id.selectbtn:
			Cursor cursor = mDbManager.select(columns, null, null, null, null, null);
			cursorAdapter.swapCursor(cursor); //커서를 이걸로 바꿔줌. 바뀌었을때 알려주는 notify어쩌구같은 기능
			break;
		case R.id.deletebtn:
			EditText num = (EditText) findViewById(R.id.deleteid);
			whereClause = "_id=?";
			whereArgs = new String[1];
			whereArgs[0]=num.getText().toString();
			mDbManager.delete(whereClause, whereArgs);
			num.setText("");
			break;
		case R.id.updatebtn:
			EditText id = (EditText) findViewById(R.id.update_id);
			EditText uphan = (EditText) findViewById(R.id.update_han);
			
			ContentValues updateRowValue = new ContentValues();
			updateRowValue.put("han", uphan.getText().toString());
			whereClause = "_id=?";
			whereArgs = new String[1];
			whereArgs[0] = id.getText().toString();
			mDbManager.update(updateRowValue, whereClause, whereArgs);
			
			id.setText("");
			uphan.setText("");
			break;	
			
		}
		cursorAdapter.swapCursor(mDbManager.select(columns, null, null, null, null, null));
		
	}
	
}
